<?php
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云存储引擎 (OSS)
 * Class Qiniu
 * @package app\common\library\storage\engine
 */
class UploadAliyun
{
    private $config;

    /**
     * 构造方法
     * Aliyun constructor.
     * @param $config
     */
    public function __construct($config)
    {
		$this->config = $config;
		$this->ossClient = new OssClient(
			$this->config['access_key_id'],
			$this->config['access_key_secret'],
			$this->config['domain'],
			true
		);
	}
    
    //post上传
    public function upload_file($fileInfo,$fileName='')
    {
        $this->fileInfo = $fileInfo;
        if($fileName){
            $this->fileName = $fileName;
        }
        $fileName = $this->buildSaveName();

        try {
            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            $result = $ossClient->uploadFile(
                $this->config['bucket'],
                $fileName,
                $this->getRealPath()
            );
        } catch (OssException $e) {
            $this->error = $e->getMessage();
            return false;
        }
        $data['file_dir'] = $this->fileDir;
        $data['file_url'] = $this->fileName;
        return $data;
    }
	
	public function upload_file_base64($fileInfo){
		$this->fileInfo = $fileInfo;

		$base64_image = str_replace(' ', '+', $fileInfo['base64']);
	    //post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){

			$fileData = base64_decode(str_replace($result[1], '', $base64_image));
			$fileName = $this->buildSaveName();

			$result = $this->ossClient->putObject(
				$this->config['bucket'], 
				$fileName, 
				$fileData
			);

            $data['file_dir'] = $this->fileDir;
			$data['file_url'] = $this->fileName;
			return $data;
		}else{
			return false;
		}
    }

    /**
     * 执行上传
     * @return bool|mixed
     */
    public function upload()
    {
        try {

            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            $result = $ossClient->uploadFile(
                $this->config['bucket'],
                $this->fileName,
                $this->getRealPath()
            );
        } catch (OssException $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
    }

    /**
     * 删除文件
     * @param $fileName
     * @return bool|mixed
     */
    public function delete($fileName)
    {
        try {
            $ossClient = new OssClient(
                $this->config['access_key_id'],
                $this->config['access_key_secret'],
                $this->config['domain'],
                true
            );
            $ossClient->deleteObject($this->config['bucket'], $fileName);
        } catch (OssException $e) {
            $this->error = $e->getMessage();
            return false;
        }
        return true;
	}

	public function setUploadFile($name = 'iFile')
    {
        // 接收上传的文件
        $this->file = $_FILES[$name];
        // $this->file =  new File($this->file['tmp_name']);

        // dump($this->file);exit;
        if (empty($this->file)) {
            // throw new Exception('未找到上传文件的信息');
        }
        // 文件信息
        $this->fileInfo = $this->file;
        
        // 生成保存文件名
        $this->fileName = $this->buildSaveName();
    }
	
	public function setUploadFileByReal($filePath)
    {
        // 设置为系统内部上传
        $this->isInternal = true;
        // 文件信息
        $this->fileInfo = [
            'name' => basename($filePath),
            'size' => filesize($filePath),
            'tmp_name' => $filePath,
            'error' => 0,
        ];
        // 生成保存文件名
        $this->fileName = $this->buildSaveName();
    }

    
	public function getFileInfo()
    {
        return $this->fileInfo;
    }
    
    public function getRealPath()
    {
        return $this->getFileInfo()['tmp_name'];
    }

    public function getFileName()
    {
        return $this->fileName;
	}

	public function getFileDir()
    {
        return $this->fileDir;
	}
	
	private function buildSaveName()
    {
		$string='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$rand='';
		for($x=0;$x<6;$x++){
			$rand.=substr($string,mt_rand(0,strlen($string)-1),1);
		}

		$this->fileDir = 'upload/'.date('Y/md', time());
        $this->ext = pathinfo($this->fileInfo['name'], PATHINFO_EXTENSION);
        if(!$this->fileName){
            $this->fileName = date('YmdHis') . substr(md5($this->fileInfo['name']), 0, 5)
                . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . ".{$this->ext}";
        }
                
		return $this->fileDir. '/' .$this->fileName;
    }

}
